Palindrome Partitioning

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

For example, given s = "aab",

Return

  1. [
  2. ["aa","b"],
  3. ["a","a","b"]
  4. ]

Solution:

  1. public class Solution {
  2. public List<List<String>> partition(String s) {
  3. List<List<String>> res = new ArrayList<List<String>>();
  4. if (s == null || s.length() == 0) {
  5. return res;
  6. }
  7. int n = s.length();
  8. // step 1. build the dp matrix to hold the palindrome information
  9. // dp[i][j] represents whether s[i] to s[j] can form a palindrome
  10. boolean[][] dp = buildMatrix(s, n);
  11. // step 2. recursively generate the list
  12. helper(s, dp, 0, n, new ArrayList<String>(), res);
  13. return res;
  14. }
  15. void helper(String s, boolean[][] dp, int start, int end, List<String> sol, List<List<String>> res) {
  16. if (start == end) {
  17. res.add(new ArrayList<String>(sol));
  18. return;
  19. }
  20. for (int i = start; i < end; i++) {
  21. if (dp[start][i]) {
  22. // s[start] to s[i] is a palindrome
  23. sol.add(s.substring(start, i + 1));
  24. helper(s, dp, i + 1, end, sol, res);
  25. sol.remove(sol.size() - 1);
  26. }
  27. }
  28. }
  29. boolean[][] buildMatrix(String s, int n) {
  30. boolean[][] dp = new boolean[n][n];
  31. for (int i = n - 1; i >= 0; i--) {
  32. for (int j = i; j < n; j++) {
  33. if (s.charAt(i) == s.charAt(j) && (j - i <= 2 || dp[i + 1][j - 1])) {
  34. dp[i][j] = true;
  35. }
  36. }
  37. }
  38. return dp;
  39. }
  40. }